package com.pubg.dao.impl;

import com.pubg.dao.BaseDao;
import com.pubg.dao.ProductTypeDao;
import com.pubg.entity.ProductType;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName ProductTypeDaoImpl
 * @Author WangYuanXiang
 * @Date 2019/4/24 17:23
 **/
public class ProductTypeDaoImpl extends BaseDao implements ProductTypeDao {
    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;
    @Override
    public List<ProductType> getList() {
        String sql = "SELECT id,`name` FROM `product_type`";
        List<ProductType> list = new ArrayList<>();
        try {
            conn = openConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                ProductType productType = new ProductType(
                        rs.getInt("id"),
                        rs.getString("name")
                );
                list.add(productType);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return list;
    }

    @Override
    public ProductType getType(int value) {
        String sql = "SELECT id,`name` FROM `product_type` where id =?";
        ProductType productType = null;
        try {
            conn = openConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,value);
            rs = pstmt.executeQuery();
            if (rs.next()){
                productType = new ProductType(
                        rs.getInt("id"),
                        rs.getString("name")
                );
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeAll(rs,pstmt,conn);
        }
        return productType;
    }
}
